package com.github.wxiaoqi.security.admin.biz;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import com.ace.cache.annotation.CacheClear;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.admin.constant.AdminCommonConstant;
import com.github.wxiaoqi.security.admin.entity.Menu;
import com.github.wxiaoqi.security.admin.entity.ResourceAuthority;
import com.github.wxiaoqi.security.admin.entity.Role;
import com.github.wxiaoqi.security.admin.entity.User;
import com.github.wxiaoqi.security.admin.mapper.ElementMapper;
import com.github.wxiaoqi.security.admin.mapper.MenuMapper;
import com.github.wxiaoqi.security.admin.mapper.ResourceAuthorityMapper;
import com.github.wxiaoqi.security.admin.mapper.RoleMapper;
import com.github.wxiaoqi.security.admin.mapper.UserMapper;
import com.github.wxiaoqi.security.admin.vo.AuthorityMenuTree;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.crm.request.QueryPersonalBaseListRequest;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.EntityUtils;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/** 
* @author: bolei
* @date：2018年4月8日 下午4:13:06 
* @description：类说明
*/

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleBiz extends BaseBiz<RoleMapper, Role> {
	
	@Autowired
    private UserMapper userMapper;
    @Autowired
    private ResourceAuthorityMapper resourceAuthorityMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private ElementMapper elementMapper;
    @Autowired
    private RoleMapper roleMapper;

    public Map<String, Object> add(Map<String, Object> param) throws Exception{
    	
    	Role role = EntityUtils.map2Bean(param, Role.class);
    	role.setCreateTime(new Date());
    	mapper.insert(role);
    	Map<String, Object> result = new HashMap<String, Object>();
    	result.put("code", ResponseCode.OK.getCode());
    	result.put("msg", ResponseCode.OK.getMessage());
    	result.put("success", true);
    	result.put("role", role);
    	return result;
	}
    
	public void modifyRoleUsers(int id, String members, String leaders) {
		// TODO Auto-generated method stub
		
	}

	/**
     * 变更role关联的菜单
     *
     * @param roleId
     * @param menus
     */
    @CacheClear(keys = {"permission:menu","permission:u"})
    public void modifyAuthorityMenu(int roleId, String[] menus) {
        resourceAuthorityMapper.deleteByAuthorityIdAndResourceType(roleId + "", AdminCommonConstant.RESOURCE_TYPE_MENU);
        List<Menu> menuList = menuMapper.selectAll();
        Map<String, String> map = new HashMap<String, String>();
        for (Menu menu : menuList) {
            map.put(menu.getId().toString(), menu.getParentId().toString());
        }
        Set<String> relationMenus = new HashSet<String>();
        relationMenus.addAll(Arrays.asList(menus));
        ResourceAuthority authority = null;
        for (String menuId : menus) {
            findParentID(map, relationMenus, menuId);
        }
        for (String menuId : relationMenus) {
            authority = new ResourceAuthority(AdminCommonConstant.AUTHORITY_TYPE_GROUP, AdminCommonConstant.RESOURCE_TYPE_MENU);
            authority.setAuthorityId(roleId + "");
            authority.setResourceId(menuId);
            authority.setParentId("-1");
            resourceAuthorityMapper.insertSelective(authority);
        }
    }
    
    private void findParentID(Map<String, String> map, Set<String> relationMenus, String id) {
        String parentId = map.get(id);
        if (String.valueOf(AdminCommonConstant.ROOT).equals(id)) {
            return;
        }
        relationMenus.add(parentId);
        findParentID(map, relationMenus, parentId);
    }

	/**
	 * 获取role拥有的菜单权限
	 * @param id
	 * @return
	 */
	public List<AuthorityMenuTree> getAuthorityMenu(int roleId) {
		List<Menu> menus = menuMapper.selectMenuByAuthorityId(String.valueOf(roleId), AdminCommonConstant.AUTHORITY_TYPE_GROUP);
        List<AuthorityMenuTree> trees = new ArrayList<AuthorityMenuTree>();
        AuthorityMenuTree node = null;
        for (Menu menu : menus) {
            node = new AuthorityMenuTree();
            node.setText(menu.getTitle());
            BeanUtils.copyProperties(menu, node);
            trees.add(node);
        }
        return trees;
	}
	
	public Object getRoleUsers(int id) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
     * 给role分配按钮级别资源权限
     *
     * @param roleId
     * @param menuId
     * @param elementId
     */
    @CacheClear(keys = {"permission:ele","permission:u"})
    public void modifyAuthorityElement(int roleId, int menuId, int elementId) {
        ResourceAuthority authority = new ResourceAuthority(AdminCommonConstant.AUTHORITY_TYPE_GROUP, AdminCommonConstant.RESOURCE_TYPE_BTN);
        authority.setAuthorityId(roleId + "");
        authority.setResourceId(elementId + "");
        authority.setParentId("-1");
        resourceAuthorityMapper.insertSelective(authority);
    }

    /**
     * 移除给role分配按钮级别资源权限
     *
     * @param roleId
     * @param menuId
     * @param elementId
     */
    @CacheClear(keys = {"permission:ele","permission:u"})
    public void removeAuthorityElement(int roleId, int menuId, int elementId) {
        ResourceAuthority authority = new ResourceAuthority();
        authority.setAuthorityId(roleId + "");
        authority.setResourceId(elementId + "");
        authority.setParentId("-1");
        resourceAuthorityMapper.delete(authority);
    }

    /**
     * 获取该角色授权的按钮或功能元素
     * @param id
     * @return
     */
	public Object getAuthorityElement(int id) {
		return elementMapper.selectAuthorityElementByRoleId(id);
	}
	
	/**
	 * 获取该角色某个菜单下得授权按钮或功能元素
	 * @param id
	 * @param menuId
	 * @return
	 */
	public Object getAuthorityMenuElement(int roleId, int menuId) {
		return elementMapper.selectAuthorityElementByRoleIdAndMenuId(roleId,menuId);
	}

	public TableResultResponse<Role> queryList(Map<String, Object> params) {
		Example example = new Example(Role.class);
		Criteria criteria = example.createCriteria();
		Object platformId = params.get("platformId");
		Object deptId = params.get("deptId");
		if(!"".equals(platformId) && null != platformId){
			//是平台管理员
			criteria.andEqualTo("platformId", platformId);
		}else {
			//系统管理员
		}
		
		if(!"".equals(deptId) && null != deptId){
			criteria.andEqualTo("deptId", deptId);
		}
		
		Page<Role> result = PageHelper.startPage(Integer.valueOf((String)(params.get("page"))), Integer.valueOf((String)params.get("limit")));
		List<Role> list = roleMapper.selectByExample(example);
		return new TableResultResponse<Role>(result.getTotal(), list);
	}

}
